package cn.me.sso.controller;
import cn.me.sso.entity.OauthClientDetailsBO;
import cn.me.sso.service.AsyncServiceImpl;
import cn.me.sso.service.OauthClientDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
/**
 * 登陆/登出controller
 *
 * @author zchcpywin10
 */
@Controller
public class LoginController {
  @Autowired
  private OauthClientDetailServiceImpl oauthClientDetailService;
  @Autowired
  private AsyncServiceImpl asynService;
  /**
   * Login string.
   *
   * @return the string
   */
  @GetMapping(value = "login")
  public String login() {
    return "login/login";
  }
  /**
   * sso server 退出后的后续操作
   *
   * @param request  the request
   * @param response the response
   * @param session  the session
   * @return string
   */
  @RequestMapping("/ssoLogout")
  public String logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    if (authentication != null) {
      new SecurityContextLogoutHandler().logout(request, response, authentication);
    }
    List<OauthClientDetailsBO> details = oauthClientDetailService.getList();
    System.out.println(details.size());
    for (OauthClientDetailsBO detail : details) {
      asynService.callClientLogout(detail.getWebClientLogoutUri(), session.getId());
    }
    return "redirect:/login";
  }
  /**
   * Index string.
   *
   * @return the string
   */
  @RequestMapping("/")
  public String index() {
    return "index";
  }
}
